package com.singleton.pattern.singleton.demo;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 *  容器式写法适用于 实例非常多的情况
 */
public class ContainerSingleton implements Serializable {
    /**
     *  私有化构造
     */
    private ContainerSingleton(){}

    /**
     *  容器
     */
    private static Map<String,Object> ioc = new ConcurrentHashMap<>();

    public static Object getBean(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        //锁 ioc
        synchronized (ioc){
            if(!ioc.containsKey(className)){
                Class<?> aClass = Class.forName(className);
                Object newInstance = aClass.newInstance();
                ioc.put(className,newInstance);
                return newInstance;
            }else{
                return ioc.get(className);
            }
        }
    }
}
